package cn.chenddcoder.operator;

import cn.hutool.core.util.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

/**
 * 房间加入逻辑
 */
@Component
public class JoinOperator {
    /**
     * 群聊map
     */
    Map<String, Set<String>> groupMap=new HashMap<>();
    /**
     * userId到群聊id
     */
    Map<String,String> userGroupMap=new HashMap<>();
    @Autowired
    private MessageOperator messageOperator;
    /**
     * 加入房间
     * @param groupId 群id
     * @param userId 用户id
     */
    public boolean join(String groupId,String userId){
        Set<String> userList=groupMap.get(groupId);
        if (userList==null){
            userList=new HashSet<>();
        }
        userList.add(userId);
        groupMap.put(groupId,userList);
        userGroupMap.put(userId,groupId);
        return true;
    }

    /**
     * 离开房间
     * @param userId 用户id
     */
    public void leave(String userId){
        if (ObjectUtil.isEmpty(userId)){
            return;
        }
        String groupId=userGroupMap.get(userId);
        Set<String> userList=groupMap.get(groupId);
        if (userList!=null){
            userList.remove(userId);
            if (userList.isEmpty()){
                groupMap.remove(groupId);
            }
        }
    }
    public boolean group(String groupId,String message) throws IOException {
        Set<String> userList = groupMap.get(groupId);
        for (String userId:userList){
            messageOperator.send(userId,message);
        }
        return true;
    }
}
